from odoo import models, fields, api
from lxml import etree
import random
import time
class noziduan(models.Model):
    _name="shilimokuai002.noziduan"
    abcdefg=""
    @api.model
    def fields_get(self, allfields=None, attributes=None):
        # 先调用父类的 fields_get 获取原始字段
        res = super(noziduan, self).fields_get(allfields, attributes)

        # 添加自定义字段 abc
        if allfields is None or 'abc' in allfields:
            res['abc'] = {
                'type': 'char',
                'string': '动态字段ABC',
                'readonly': False,
                'required': False,
                'selectable': True,
                'sortable': True,
                'store': False,
            }

        return res
    @api.model
    def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
        # 调用原始 search_read 获取记录数据
        records = self.search(domain or [], offset=offset, limit=limit, order=order)
        result = records.read(fields)

        # 添加虚拟字段 abc 的值
        for record in result:
            record['abc'] = '虚拟值_' + record.get('name', '未知')

        return result      
    @api.model
   
    def web_search_read(self, domain, specification, offset=0, limit=None, order=None, count_limit=None):
        dynamic_field = self.__class__.abcdefg
        # 构造模拟数据
        fake_data = [
            {'id': 1, 'name': '张三'},
            {'id': 2, 'name': '李四'},
            {'id': 3, 'name': '王五'},
        ]

        # 添加虚拟字段 abc
        for rec in fake_data:
            rec[dynamic_field] = 'web值_' + rec['name']

        # 构造返回结构，模拟 web_search_read 的格式
        return {
            'length': len(fake_data),   # 总条数
            'records': fake_data        # 记录列表
        }

    def _generate_dynamic_field_name(self):
        return f"changge{int(time.time())}_{random.randint(1000, 9999)}"       

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        result = super().fields_view_get(view_id, view_type, toolbar, submenu)

        # 只修改 list 视图
        if view_type == 'list' and 'arch' in result:
            arch = etree.fromstring(result['arch'])
            etree.SubElement(arch, 'field', name='abc')  # 添加字段
            result['arch'] = etree.tostring(arch, encoding='unicode')
        return result


    @api.model
    def get_views(self, views, options=None):
        """重写以动态生成视图 arch"""
        dynamic_field = self._generate_dynamic_field_name()
        self.__class__.abcdefg=  dynamic_field 
        # 调用父类的方法，获取视图数据
        result = super().get_views(views, options=options)

        # 确保 result 中有 views 字段
        if "views" in result:
            for view_key, view in result["views"].items():
                # 获取当前视图的类型
                view_type = view.get("arch")  # 'arch' 是包含 XML 的关键字
                
                # 如果视图类型是 'list'，我们修改它的 arch
                if view_key == "list" and view_type:
                    # 解析原始的 XML 内容
                    arch = etree.fromstring(view["arch"])

                    # 动态向树视图中添加字段（如 'abc'）
                    etree.SubElement(arch, "field", name=f'{dynamic_field}')

                    # 更新 arch 字段为修改后的 XML 字符串
                    view["arch"] = etree.tostring(arch, encoding="unicode")

# 手动更新 models 部分
        if "models" in result and self._name in result["models"]:
            model_data = result["models"][self._name]
            fields = model_data.get("fields", {})
            if self.abcdefg not in fields:
                fields[f'{dynamic_field}'] = {
                    'type': 'char',
                    'string': f'{dynamic_field}',
                    'readonly': False,
                    'required': False,
                    'selectable': True,
                    'sortable': True,
                    'store': False,
                }
        return result